<template>
  <!--view class="cjMp3" :class="{ 'on' : isStart }" @tap="onToggle"></view-->
</template>
<script>
export default {
  props : ['state'],
  data() {
    return {
      isStart : true,
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init(){
      //<audio style="display:none; height: 0" id="bg-music" preload="auto" src="bgm.mp3"></audio>
      //音乐自动播放
      let audio = document.createElement('audio');
      audio.setAttribute('loop',true);
      audio.setAttribute('id','bg-music');
      audio.setAttribute('preload','auto');
      audio.setAttribute('title',this.state.title);
      audio.setAttribute('src',require('@/static/music.mp3'));
      document.querySelector('body').appendChild(audio);
      var media = document.querySelector('#bg-music');
      media.addEventListener('play',() => {
        this.isStart = true;
        console.log('onPlay');
        this.$emit('input',this.isStart);
      })
      media.addEventListener('pause',() => {
        this.isStart = false;
        console.log('onPaused');
        this.$emit('input',this.isStart);
      })

      this.media = media;
      autoPlayMusic();
      audioAutoPlay();
      function audioAutoPlay() {
          var audio = document.getElementById('bg-music');
          //audio.play();
          document.addEventListener("WeixinJSBridgeReady", function () {
              audio.play();
          }, false);
      }
      // 音乐播放
      function autoPlayMusic() {
          // 自动播放音乐效果，解决浏览器或者APP自动播放问题
          function musicInBrowserHandler() {
              musicPlay(true);
              document.body.removeEventListener('touchstart', musicInBrowserHandler);
          }
          document.body.addEventListener('touchstart', musicInBrowserHandler);
          // 自动播放音乐效果，解决微信自动播放问题
          function musicInWeixinHandler() {
              musicPlay(true);
              document.addEventListener("WeixinJSBridgeReady", function () {
                  musicPlay(true);
              }, false);
              document.removeEventListener('DOMContentLoaded', musicInWeixinHandler);
          }
          document.addEventListener('DOMContentLoaded', musicInWeixinHandler);
      }
      function musicPlay(isPlay) {
          var media = document.querySelector('#bg-music');
          if (isPlay && media.paused) {
              media.play();
          }
          if (!isPlay && !media.paused) {
              media.pause();
          }
      }
    },
    onToggle(){
      if(this.isStart){
        this.stopMp3();
      }else{
        this.playMp3();
      }
    },
    playMp3(){
      this.media.play();
    },
    stopMp3(){
      this.media.pause();
    },
    testAutoPlay () {
    }
  }
}
</script>
